package com.shiqupad.order.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.shiqupad.order.R;
import com.shiqupad.order.adapter.CartAdapter;
import com.shiqupad.order.adapter.DishAdapter2;
import com.shiqupad.order.adapter.DishTypeAdapter2;
import com.shiqupad.order.cache.CartCacheManager;
import com.shiqupad.order.listener.GetDishDetailListener;
import com.shiqupad.order.listener.GetShopDishListener;
import com.shiqupad.order.listener.IsNeedTableFeeListener;
import com.shiqupad.order.listener.MenuChangeListener;
import com.shiqupad.order.listener.PostOrderListener;
import com.shiqupad.order.presenter.GetDishDetailPresenter;
import com.shiqupad.order.presenter.GetShopDishPresenter;
import com.shiqupad.order.presenter.IsNeedTableFeePresenter;
import com.shiqupad.order.presenter.PostOrderPresenter;
import com.shiqupad.order.ui.DishComboDialog;
import com.shiqupad.order.ui.DishSpecDialog;
import com.shiqupad.order.ui.InputMessageDialog;
import com.shiqupad.order.util.MathUtil;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.com.dreamtouch.common.DTLog;
import cn.com.dreamtouch.magicbox_common.util.CommonConstant;
import cn.com.dreamtouch.magicbox_general_ui.activity.MBBaseActivity;
import cn.com.dreamtouch.magicbox_general_ui.ui.ActionSheetDialog;
import cn.com.dreamtouch.magicbox_general_ui.util.MyLogger;
import cn.com.dreamtouch.magicbox_general_ui.util.RxBusUtil;
import cn.com.dreamtouch.magicbox_http_client.network.model.DishSetDetail;
import cn.com.dreamtouch.magicbox_http_client.network.model.DishSkuEquals;
import cn.com.dreamtouch.magicbox_http_client.network.model.DishTasteBean;
import cn.com.dreamtouch.magicbox_http_client.network.model.DishUnitBean;
import cn.com.dreamtouch.magicbox_http_client.network.model.GetDishDetailResponse;
import cn.com.dreamtouch.magicbox_http_client.network.model.GetShopDishResponse;
import cn.com.dreamtouch.magicbox_http_client.network.model.IsNeedTableFeeResponse;
import cn.com.dreamtouch.magicbox_http_client.network.model.OrderParam;
import cn.com.dreamtouch.magicbox_http_client.network.model.PostOrderResponse;
import cn.com.dreamtouch.magicbox_http_client.network.model.RxEvent;
import cn.com.dreamtouch.magicbox_repository.datasource.local.UserLocalData;
import cn.com.dreamtouch.magicbox_repository.datasource.remote.UserRemoteData;
import cn.com.dreamtouch.magicbox_repository.repository.UserRepository;
import drawthink.expandablerecyclerview.bean.RecyclerViewData;


public class NewShopCartActivity2 extends MBBaseActivity implements
        GetShopDishListener, InputMessageDialog.IInputMessageDialogCallback,
        GetDishDetailListener, DishComboDialog.IDishComboDialogCallBack,
        DishSpecDialog.IDishSpecDialogCallBack, MenuChangeListener, PostOrderListener, IsNeedTableFeeListener {

    @Bind(R.id.back)
    ImageView ivBack;
    @Bind(R.id.cont_common_head_right_tv)
    TextView ivClear;
    @Bind(R.id.act_shop_cart_rcv)
    ListView listView2;
    // RecyclerView mLeftRv;
    @Bind(R.id.act_shop_cart_dish_rv)
    GridView mCenterDishRv;

    @Bind(R.id.act_shop_cart_right)
    ListView mRightRv;
    @Bind(R.id.rootview)
    LinearLayout rootview;
    @Bind(R.id.act_shop_cart_left_et)
    EditText etRemark;
    @Bind(R.id.act_shop_cart_left_count)
    TextView tvCount;
    @Bind(R.id.act_shop_cart_left_price)
    TextView tvPriceTotal;
    @Bind(R.id.cont_common_head_center_tv)
    TextView tvTableName;
    @Bind(R.id.act_cart_left_sure_tv)
    TextView tvSure;
    @Bind(R.id.act_shop_cart_search_et)
    EditText etSearch;
    @Bind(R.id.scl)
    ScrollView scrollView;
    private DishTypeAdapter2 mDishTypeAdapter;
    // private LeftNewDIshAdapter mLeftDishAdapter;
    private DishAdapter2 mDishAdapter;
    private List<GetShopDishResponse.TwoShopDish> mTwoShopDishList;
    private GetShopDishPresenter mGetShopDishPresenter;
    private PostOrderPresenter mPostOrderPresenter;
    private GetDishDetailPresenter mGetDishDetailPresenter;
    private IsNeedTableFeePresenter mIsNeedTableFeePresenter;
    private List<GetShopDishResponse.OneShopDish> mGetResponseDataList;
    private List<GetShopDishResponse.OneShopDish> mGetResponseDataList2;
    private List<GetShopDishResponse.OneShopDish> mOneShopDishList;

    // private List<GetShopDishResponse.TwoShopDish> mLeftTwoShopDisheList;
    private int mSelection;
    private int mPosition = 0;
    private InputMessageDialog inputMessageDialog;
    private DishComboDialog mDishComboDialog;
    private DishSpecDialog mDishSpecDialog;
    private String mShopId;
    private List<RecyclerViewData> mDatas;
    private CartAdapter cartAdapter;
    private List<GetShopDishResponse.TwoShopDish> cartList = new ArrayList<>();
    private List<GetShopDishResponse.TwoShopDish> categoryList = new ArrayList<>();
    // private GetShopDishResponse.TwoShopDish specDishInfo;//有规格口味的菜品
    int tableId;
    String tableName;
    private String tableFee;
    private int dinnerPeople;
    InputMethodManager mInputMethodManager;
    private boolean isAccount;
    private String orderId;
    private String shopType;
    private List<GetShopDishResponse.TwoShopDish> mustOrderDishs = new ArrayList<>();
    private GetShopDishResponse.TwoShopDish  preHasTasteTwoShopDish;
    @Override
    protected void onResume() {
        super.onResume();
        if (tableId != 0) {
            List<GetShopDishResponse.TwoShopDish> cartCacheList = CartCacheManager.getInstance(this).getCartList(tableId);

            if (cartCacheList != null && cartCacheList.size() > 0) {
                cartList.clear();
                cartList.addAll(cartCacheList);
                updateSomeView();
            }
        }

    }

    @Override
    protected void onStop() {
        super.onStop();
        if (tableId != 0 && cartList.size() > 0) {//tableId - cartList
            CartCacheManager.getInstance(this).updateCart(tableId, cartList);
        }
    }

    @Override
    protected void initVariables() {
        super.initVariables();
        mInputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

        mGetResponseDataList = new ArrayList<>();
        mGetResponseDataList2 = new ArrayList<>();
        shopType = UserLocalData.getInstance(this).getShopType();
        tableId = getIntent().getIntExtra(CommonConstant.Args.TABLE_ID, 0);
        tableName = getIntent().getStringExtra(CommonConstant.Args.TABLE_NAME);
        dinnerPeople = getIntent().getIntExtra(CommonConstant.Args.DINNER_NUM, 0);
        mShopId = UserLocalData.getInstance(this).getShopID();
        mGetShopDishPresenter = new GetShopDishPresenter(UserRepository.getInstance(UserLocalData.getInstance(this)
                , UserRemoteData.getInstance(this)
        ), this);
        mPostOrderPresenter = new PostOrderPresenter(UserRepository.getInstance(UserLocalData.getInstance(this)
                , UserRemoteData.getInstance(this)
        ), this);
        mGetDishDetailPresenter = new GetDishDetailPresenter(UserRepository.getInstance(UserLocalData.getInstance(this)
                , UserRemoteData.getInstance(this)
        ), this);
        mIsNeedTableFeePresenter = new IsNeedTableFeePresenter(UserRepository.getInstance(UserLocalData.getInstance(this)
                , UserRemoteData.getInstance(this)
        ), this);
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        setContentView(R.layout.activity_shop_cart2);
        ButterKnife.bind(this);
        tvTableName.setText(MessageFormat.format("{0}", tableName));
        initLeftRVAndAdapter();
        initCenterRecyclerViewAndAdapter();
        initRightRvAndAdapter();
        initEtSearch();
    }

    private void initEtSearch() {
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                for (int i = 0; i < mOneShopDishList.size(); i++) {
                    GetShopDishResponse.OneShopDish oneShopDish = mOneShopDishList.get(i);
                    List<GetShopDishResponse.TwoShopDish> dishList = oneShopDish.getDishList();
                    for (int j = 0; j < dishList.size(); j++) {
                        String dishName = dishList.get(j).getDishName();
                        if (dishName.equals(s.toString())) {
                            mSelection = i;
                            mDishTypeAdapter.setSelection(mSelection);
                            initDishData(mGetResponseDataList, mSelection);
                        }
                    }
                }

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    private void initRightRvAndAdapter() {
        mOneShopDishList = new ArrayList<>();
        mDishTypeAdapter = new DishTypeAdapter2(mOneShopDishList,this);
      //  mRightRv.setLayoutManager(new LinearLayoutManager(this));
        mRightRv.setAdapter(mDishTypeAdapter);
       // mRightRv.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));
        mRightRv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mSelection = position;
                mDishTypeAdapter.setSelection(position);
                initDishData(mGetResponseDataList, position);
            }
        });
    }

    private void initCenterRecyclerViewAndAdapter() {
        mTwoShopDishList = new ArrayList<>();
        mDishAdapter = new DishAdapter2( mTwoShopDishList,
              this, this);
       // mCenterDishRv.setLayoutManager(new GridLayoutManager(this, 3));
        mCenterDishRv.setAdapter(mDishAdapter);
        mCenterDishRv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                chooseShopDish(position);
            }
        });

    }

    private void chooseShopDish(int position) {
        mPosition = position;
        GetShopDishResponse.TwoShopDish twoShopDish = mTwoShopDishList.get(mPosition);
        // specDishInfo = twoShopDish;
        if (twoShopDish.getLimitNumber().equals("0")) {
            DTLog.showMessageShort(this, "该物品已售罄");
        } else if (twoShopDish.getIsHaveTaste().equals("1") ||
                twoShopDish.getIsHaveUnit().equals("1") ||
                twoShopDish.getIsSet().equals("1")) {
            preHasTasteTwoShopDish = twoShopDish;
            mGetDishDetailPresenter.getDishDetail(mShopId, twoShopDish.getShopDishID());

        } else if (twoShopDish.getIsMarketPriceDish().equals("1")) {
            inputPrice();
        } else {

        }
    }


    private void inputPrice() {
        if (inputMessageDialog == null) {
            inputMessageDialog = new InputMessageDialog(this, "时价菜"
                    , "请输入价格", this);
            inputMessageDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    inputMessageDialog = null;
                }
            });

        }
        inputMessageDialog.show();
    }

    @Override
    protected void loadData() {
        super.loadData();
        mGetShopDishPresenter.getShopDish();

    }

    private void initLeftRVAndAdapter() {
       /* mLeftTwoShopDisheList = new ArrayList<>();
        mDatas = new ArrayList<>();
        mLeftDishAdapter = new LeftNewDIshAdapter(this,mDatas);
        mLeftRv.setLayoutManager(new LinearLayoutManager(this));
        mLeftRv.setAdapter(mLeftDishAdapter);
        mLeftRv.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));*/
        cartAdapter = new CartAdapter(cartList, this);
        cartAdapter.setMenuChangeListener(new MenuChangeListener() {
            @Override
            public void onMenuChange(int position, int num) {
                mLogger.e(position + "...." + num);
                addDishForCart(position, num);
            }
        });
        listView2.setAdapter(cartAdapter);
    }

    private void addDishForCart(int position, int num) {
        GetShopDishResponse.TwoShopDish twoShopDish = cartList.get(position);
        int count = num - twoShopDish.getCartNum();
        twoShopDish.setCartNum(num);
        for (int i = 0; i < mGetResponseDataList.size(); i++) {
            List<GetShopDishResponse.TwoShopDish> dishInfoList = mGetResponseDataList.get(i).getDishList();
            if (dishInfoList == null) {
                return;
            }
            for (int j = 0; j < dishInfoList.size(); j++) {
                GetShopDishResponse.TwoShopDish dish = dishInfoList.get(j);
                if (twoShopDish.getDishID() == null || dish.getDishID() == null) {
                    return;
                }
                if (twoShopDish.getDishID().equals(dish.getDishID())) {
                    if (twoShopDish.getIsHaveUnit().equals("1") ||
                            twoShopDish.getIsHaveTaste().equals("1")
                            || twoShopDish.getIsSet().equals("1")
                            || twoShopDish.getIsMarketPriceDish().equals("1")) {
                        dish.setCartNum(num);
                    } else {
                        dish.setCartNum(num);
                    }
                    //mDishAdapter.notifyDataSetChanged(j);
                    mDishAdapter.notifyDataSetChanged();
                }
            }
        }
        if (num == 0) {
            cartList.remove(position);
        }
        updateSomeView();
    }


    @OnClick({R.id.back, R.id.cont_common_head_right_tv, R.id.act_cart_left_sure_tv
            , R.id.act_shop_cart_left_et
    })
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                //overridePendingTransition(R.anim.activity_open, R.anim.activity_close);
                break;

            case R.id.cont_common_head_right_tv:
                resetDataSet();
                break;

            case R.id.act_cart_left_sure_tv:
                etRemark.setFocusable(false);//设置输入框不可聚焦，即失去焦点和光标
                if (mInputMethodManager.isActive()) {
                    mInputMethodManager.hideSoftInputFromWindow(etRemark.getWindowToken(), 0);// 隐藏输入法
                }
                orderOrAccount();
                break;
            case R.id.act_shop_cart_left_et:
                etRemark.setFocusable(true);//设置输入框可聚集
                etRemark.setFocusableInTouchMode(true);//设置触摸聚焦
                etRemark.requestFocus();//请求焦点
                etRemark.findFocus();//获取焦点
                mInputMethodManager.showSoftInput(etRemark, InputMethodManager.SHOW_FORCED);// 显示输入法
                break;
        }
    }

    private void orderOrAccount() {
        if (cartList.size() <= 0) {
            DTLog.showMessageShort(this, "请先选择商品");
            return;
        }
        new ActionSheetDialog(NewShopCartActivity2.this).builder()
                /* .setTitle("确认退出吗？")*/
                .addSheetItem("下单", ActionSheetDialog.SheetItemColor.Red, new ActionSheetDialog.OnSheetItemClickListener() {
                    @Override
                    public void onClick(int which) {
                        mLogger.e("1");
                        mPostOrderPresenter.postOrder(generateOrderParam());
                    }
                }).addSheetItem("结账", ActionSheetDialog.SheetItemColor.Red, new ActionSheetDialog.OnSheetItemClickListener() {
            @Override
            public void onClick(int which) {
                isAccount = true;
                mPostOrderPresenter.postOrder(generateOrderParam());
            }
        })
                .setCancelable(true)
                .show();

    }

    @Override
    public void getShopDishSuccess(GetShopDishResponse getShopDishResponse) {
        List<GetShopDishResponse.OneShopDish> data = getShopDishResponse.getData();


        mIsNeedTableFeePresenter.isNeedTableFee(String.valueOf(tableId), mShopId);
        mGetResponseDataList.addAll(getShopDishResponse.getData());
        mGetResponseDataList2.addAll(getShopDishResponse.getData());

        /*===============*/
        for (int i = 0; i < mGetResponseDataList2.size(); i++) {
            GetShopDishResponse.OneShopDish oneShopDish2= mGetResponseDataList2.get(i);
            List<GetShopDishResponse.TwoShopDish> dishDishList2 = oneShopDish2.getDishList();
            for (int j = 0; j < dishDishList2.size(); j++) {
                GetShopDishResponse.TwoShopDish twoShopDish2 = dishDishList2.get(j);
                if (twoShopDish2.getIsMustOrder().equals("1")) {
                    twoShopDish2.setCartNum(0);
                    mustOrderDishs.add(twoShopDish2);
                    mLogger.e(twoShopDish2.toString());
                }
            }

        }

        initTypeData(mGetResponseDataList);
        initDishData(mGetResponseDataList, 0);
    }

    private void initDishData(List<GetShopDishResponse.OneShopDish> getResponseDataList, int position) {


        mTwoShopDishList.clear();
        for (int i = 0; i < getResponseDataList.size(); i++) {
            if (position == i) {
                List<GetShopDishResponse.TwoShopDish> dishList = getResponseDataList.get(position).getDishList();
                for (int j = 0; j < dishList.size(); j++) {
                    GetShopDishResponse.TwoShopDish twoShopDish = dishList.get(j);
                    if(twoShopDish.getIsMustOrder() .equals("1")){
                        dishList.remove(j);
                    }
                }
                mTwoShopDishList.addAll(dishList);
            }

        }
        mDishAdapter.notifyDataSetChanged();

        handleDataForCartList();
    }

    private void initTypeData(List<GetShopDishResponse.OneShopDish> getResponseDataList) {

        mOneShopDishList.clear();
        mOneShopDishList.addAll(getResponseDataList);
       // mDishTypeAdapter.refresh(mOneShopDishList);
    }

    @Override
    public void basicFailure(String prompt) {
        //DTLog.showMessage(this, prompt);
    }

    @Override
    public void getInputMessage(String message) {
        if (inputMessageDialog != null) {
            inputMessageDialog.dismiss();
            inputMessageDialog = null;
        }
        GetShopDishResponse.TwoShopDish newTwoShopDish = generateDishContainPrice(message);

        if (cartList.size() == 0) {
            cartList.add(newTwoShopDish);

        } else {
            boolean isAdd = false;
            for (int i = 0; i < cartList.size(); i++) {
                GetShopDishResponse.TwoShopDish twoShopDish = cartList.get(i);
                if (twoShopDish.getDishID().equals(newTwoShopDish.getDishID())) {
                    twoShopDish.setPrice(newTwoShopDish.getPrice());
                    isAdd = true;
                   // mDishAdapter.notifyItemChanged(i);
                    mDishAdapter.notifyDataSetChanged();
                    break;
                }
            }
            if(!isAdd){
                cartList.add(newTwoShopDish);
            }

        }
        updateSomeView();
    }


    //选择规格
    private void showSpecDialog(GetDishDetailResponse getDishDetailResponse, final int selection, final int position) {
        GetDishDetailResponse.DataBean dataBean = getDishDetailResponse.getData();

        List<DishTasteBean> tasteList = new ArrayList<>();
        List<DishTasteBean> feedList = new ArrayList<>();
        List<DishUnitBean> unitList = new ArrayList<>();

        if (dataBean.getDishTasteList() != null) {
            for (int i = 0; i < dataBean.getDishTasteList().size(); i++) {
                DishTasteBean bean = dataBean.getDishTasteList().get(i);
                if (bean.getType() == 1) {//口味即忌口
                    tasteList.add(bean);
                } else if (bean.getType() == 4) {//加料
                    feedList.add(bean);
                }
            }
        }
        if (dataBean.getDishUnitList() != null)
            unitList.addAll(dataBean.getDishUnitList());


        if (dataBean.getIsSet() == 1) {
            if (mDishComboDialog == null) {
                mDishComboDialog = new DishComboDialog(this, dataBean);
                mDishComboDialog.setCallBack(this, selection, position);
                mDishComboDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        mDishComboDialog = null;
                    }
                });
            }
            mDishComboDialog.show();
        } else if (dataBean.getIsHaveUnit() == 1 || dataBean.getIsHaveTaste() == 1) {
            if (mDishSpecDialog == null) {
                mDishSpecDialog = new DishSpecDialog(this, dataBean);
                mDishSpecDialog.setDataSet(tasteList, feedList, unitList);
                mDishSpecDialog.setCallBack(this);
                mDishSpecDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        mDishSpecDialog = null;
                    }
                });
            }

            mDishSpecDialog.show();
        }
    }


    @Override
    public void getDishDetailSuccess(GetDishDetailResponse getDishDetailResponse) {
        showSpecDialog(getDishDetailResponse, mSelection, mPosition);
    }

    @Override
    public void onDishComboDialogCallBack(List<DishSetDetail> comboList, int selection, int position) {
        if (mDishComboDialog != null) {
            mDishComboDialog.dismiss();
            mDishComboDialog = null;
        }
        for (int i = 0; i < comboList.size(); i++) {
            MyLogger.kLog().e(comboList.get(i).toString());
        }
        mTwoShopDishList.get(position).setCartNum(1);
        //mDishAdapter.notifyItemChanged(position);
        mDishAdapter.notifyDataSetChanged();
        /*if(specDishInfo == null){
            return;
        }*/
        GetShopDishResponse.TwoShopDish newBean = (GetShopDishResponse.TwoShopDish) preHasTasteTwoShopDish.clone();
        newBean.setComboList(comboList);
        newBean.setComboDesc(new Gson().toJson(comboList));

        newBean.setCartNum(1);
        preHasTasteTwoShopDish = null;

        DishSkuEquals skuNew = new DishSkuEquals();
        skuNew.setDishCombo(newBean.getComboDesc());

        if (!cartList.contains(newBean)) {
            cartList.add(newBean);
        } else {
            boolean isAdd = false;
            for (int i = 0; i < cartList.size(); i++) {
                GetShopDishResponse.TwoShopDish oldBean = cartList.get(i);

                if (newBean.getDishID().equals(oldBean.getDishID())) {//dishID相同的菜
                    DishSkuEquals skuOld = new DishSkuEquals();
                    skuOld.setDishCombo(oldBean.getComboDesc());

                    if (skuNew.equals(skuOld)) {//规格口味加料均相同的菜
                        oldBean.setCartNum(oldBean.getCartNum() + 1);
                        isAdd = true;
                    }
                }
            }
            if (!isAdd)
                cartList.add(newBean);
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                updateSomeView();
            }
        });

    }

    @Override
    public void onSpecDialogCallBack(DishUnitBean selectUnit,
                                     DishTasteBean selectTaste,
                                     List<DishTasteBean> feedingList) {
       /* if(specDishInfo == null){
            return;
        }*/
        if (mDishSpecDialog != null) {
            mDishSpecDialog.dismiss();
            mDishSpecDialog = null;
        }
        GetShopDishResponse.TwoShopDish twoShopDish = null;
        if(preHasTasteTwoShopDish != null) {
           twoShopDish = (GetShopDishResponse.TwoShopDish) preHasTasteTwoShopDish.clone();
        }
        if (selectUnit != null) {
            twoShopDish.setDishUnitName(selectUnit.getUnitName());
            twoShopDish.setDishUnitID(selectUnit.getDishUnitID());
            twoShopDish.setPrice(selectUnit.getPrice());
            twoShopDish.setDishUnit(selectUnit);
        }
        //加料
        for (DishTasteBean tasteBean : feedingList) {
            twoShopDish.setPrice(twoShopDish.getPrice() +
                    tasteBean.getRisePrice() * tasteBean.getValue());
        }
        twoShopDish.setFeedList(feedingList);
        Gson gson = new Gson();

        twoShopDish.setFeedDesc(gson.toJson(feedingList));
        //口味
        if (selectTaste != null) {
            twoShopDish.setDishTsateName(selectTaste.getTasteName());
            twoShopDish.setDishTasteID(selectTaste.getDishTasteID());
            twoShopDish.setDishTaste(selectTaste);
        }

        twoShopDish.setCartNum(1);
        preHasTasteTwoShopDish.setCartNum(preHasTasteTwoShopDish.getCartNum()+1);
        preHasTasteTwoShopDish = null;
        mDishAdapter.notifyDataSetChanged();
       // mDishAdapter.notifyItemChanged(mPosition);
       /* specDishInfo.setCartNum(specDishInfo.getCartNum() + 1);
        specDishInfo = null;*/

        DishSkuEquals skuNew = new DishSkuEquals();
        skuNew.setDishFeed(twoShopDish.getFeedDesc());
        skuNew.setDishTaste(twoShopDish.getDishTasteID());
        skuNew.setDishUnit(twoShopDish.getDishUnitID());
        mLogger.e(skuNew.toString());
        if (!cartList.contains(twoShopDish)) {
            cartList.add(twoShopDish);
        } else {
            boolean isAdd = false;
            for (int i = 0; i < cartList.size(); i++) {
                GetShopDishResponse.TwoShopDish oldBean = cartList.get(i);

                if (twoShopDish.getDishID().equals(oldBean.getDishID())) {//dishID相同的菜
                    DishSkuEquals skuOld = new DishSkuEquals();
                    skuOld.setDishFeed(oldBean.getFeedDesc());
                    skuOld.setDishTaste(oldBean.getDishTasteID());
                    skuOld.setDishUnit(oldBean.getDishUnitID());
                    mLogger.e(skuOld.toString());
                    if (skuNew.equals(skuOld)) {//规格口味加料均相同的菜
                        oldBean.setCartNum(oldBean.getCartNum() + 1);
                        isAdd = true;
                    }
                }
            }
            if (!isAdd)
                cartList.add(twoShopDish);
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                updateSomeView();
            }
        });
    }


    @Override
    public void onMenuChange(int position, int num) {
        mLogger.e(position + "...." + num);
        addDishForMenu(position, num);
    }

    private void addDishForMenu(int position, int num) {
        GetShopDishResponse.TwoShopDish twoShopDish = null;
        for (int i = 0; i < mGetResponseDataList.size(); i++) {
            if (i == mPosition) {
                GetShopDishResponse.OneShopDish oneShopDish = mGetResponseDataList.get(i);
                List<GetShopDishResponse.TwoShopDish> dishList = oneShopDish.getDishList();
                for (int j = 0; j < dishList.size(); j++) {
                    twoShopDish = mTwoShopDishList.get(position);
                    twoShopDish.setCartNum(num);
                   // mDishAdapter.notifyItemChanged(position);
                    mDishAdapter.notifyDataSetChanged();
                }
            }

        }
        boolean isAdd =false;
        for (int i = 0; i < cartList.size(); i++) {
            GetShopDishResponse.TwoShopDish twoShopDish1 = cartList.get(i);
            if(twoShopDish1.getDishID().equals(twoShopDish.getDishID())){
                twoShopDish1.setCartNum(twoShopDish.getCartNum());
                isAdd = true;
            }
        }
        if(!isAdd){
            cartList.add(twoShopDish);
        }
       /* if (cartList.contains(twoShopDish)) {
            cartList.get(cartList.indexOf(twoShopDish))
                    .setCartNum(twoShopDish.getCartNum());
        } else {
            cartList.add(twoShopDish);
        }*/
        updateSomeView();

    }

    double total = 0;

    private void updateSomeView() {
        if (cartList.size() > 0) {
            for (int i = 0; i < cartList.size(); i++) {
                GetShopDishResponse.TwoShopDish twoShopDish = cartList.get(i);
                if(twoShopDish != null) {
                    if (twoShopDish.getCartNum() == 0) {
                        cartList.remove(i);
                    }
                }

            }
           // listView2.smoothScrollToPosition(cartList.size()-1);
            scrollView.fullScroll(ScrollView.FOCUS_DOWN);
            // tvEmpty.setVisibility(View.GONE);
            cartAdapter.notifyDataSetChanged();
          //  mDishAdapter.refresh(mTwoShopDishList);
            tvCount.setText(cartList.size() + "");

            for (int i = 0; i < cartList.size(); i++) {
                GetShopDishResponse.TwoShopDish twoShopDish = cartList.get(i);
                if(twoShopDish!=null){
                    int cartNum = twoShopDish.getCartNum();
                    double price = twoShopDish.getPrice();
                    total += cartNum * price;
                }

            }
            tvPriceTotal.setText(MessageFormat.format("{0}", total));
            total = 0;

            mDishTypeAdapter.notifyDataSetChanged();

            //tvConfirm.setBackgroundColor(ContextCompat.getColor(this, R.color.red));
            // tvConfirm.setOnClickListener(this);
        } else {
            //tvEmpty.setVisibility(View.VISIBLE);
            cartAdapter.notifyDataSetChanged();
            tvPriceTotal.setText("0");
            tvCount.setText("0");
            mDishTypeAdapter.notifyDataSetChanged();
            //adapter.notifyDataSetChanged();
            //tvConfirm.setBackgroundColor(Color.parseColor("#b3b3b3"));
            //tvConfirm.setOnClickListener(null);
        }

        //  updateBageView();
    }

    private void updateBageView() {
        if (mGetResponseDataList == null || mGetResponseDataList.size() < 1) {
            return;
        }
        List<GetShopDishResponse.TwoShopDish> dishList = mGetResponseDataList.get(mPosition).getDishList();
        for (int i = 0; i < cartList.size(); i++) {
            GetShopDishResponse.TwoShopDish twoShopDish = cartList.get(i);
            for (int j = 0; j < dishList.size(); j++) {
                String dishID = dishList.get(j).getDishID();
                if (twoShopDish.getDishID().equals(dishID)) {
                    categoryList.add(twoShopDish);
                }
            }
        }
        // mDishTypeAdapter.setNum(categoryList.size());
    }

    //时价菜
    private GetShopDishResponse.TwoShopDish generateDishContainPrice(String input) {
        GetShopDishResponse.TwoShopDish newDishPriceBean = new GetShopDishResponse.TwoShopDish();
        GetShopDishResponse.TwoShopDish twoShopDish = mTwoShopDishList.get(mPosition);
        newDishPriceBean.setCartNum(1);
        twoShopDish.setCartNum(1);
        //mDishAdapter.notifyItemChanged(mPosition);
        mDishAdapter.notifyDataSetChanged();
        newDishPriceBean.setDishTypeID(twoShopDish.getDishTypeID());
        newDishPriceBean.setDishID(twoShopDish.getDishID());
        newDishPriceBean.setSortNumber(twoShopDish.getSortNumber());
        newDishPriceBean.setPrice(Double.valueOf(input));
        newDishPriceBean.setCode(twoShopDish.getCode());
        newDishPriceBean.setDishName(twoShopDish.getDishName());
        newDishPriceBean.setIsHaveTaste(twoShopDish.getIsHaveTaste());
        newDishPriceBean.setIsHaveUnit(twoShopDish.getIsHaveUnit());
        newDishPriceBean.setLimitNumber(twoShopDish.getLimitNumber());
        newDishPriceBean.setIsSet(twoShopDish.getIsSet());
        newDishPriceBean.setIsMarketPriceDish(twoShopDish.getIsMarketPriceDish());
        newDishPriceBean.setTotalSaleNumber(twoShopDish.getTotalSaleNumber());

        return newDishPriceBean;
    }

    //重置数据源
    private void resetDataSet() {
        if (tableId != 0) {
            CartCacheManager.getInstance(this).clearCart(tableId);

        }
        for (int i = 0; i < mGetResponseDataList.size(); i++) {
            for (GetShopDishResponse.TwoShopDish dish : mGetResponseDataList.get(i).getDishList()) {
                dish.setCartNum(0);
            }
        }
        if (mDishAdapter != null) {
            mDishAdapter.notifyDataSetChanged();
            cartAdapter.notifyDataSetChanged();
        }
        cartList.clear();
        updateSomeView();
    }

    //基于购物车数据处理数据
    private void handleDataForCartList() {
        for (int i = 0; i < cartList.size(); i++) {
            GetShopDishResponse.TwoShopDish twoShopDish = cartList.get(i);
            for (int j = 0; j < mGetResponseDataList.size(); j++) {
                List<GetShopDishResponse.TwoShopDish> dishInfoList = mGetResponseDataList.get(j).getDishList();
                for (int k = 0; k < dishInfoList.size(); k++) {
                    GetShopDishResponse.TwoShopDish dish = dishInfoList.get(k);
                    if (dish.getDishID().equals(twoShopDish.getDishID())) {
                        dish.setCartNum(twoShopDish.getCartNum());
                        //mDishAdapter.notifyItemChanged(k);
                        mDishAdapter.notifyDataSetChanged();
                    }
                }
            }
        }
    }

    //生成订单参数
    private OrderParam generateOrderParam() {
        for (int i = 0; i < mustOrderDishs.size(); i++) {
            mustOrderDishs.get(i).setCartNum(dinnerPeople);
        }
        ArrayList<OrderParam.OrderDetailParam> detailParams = new ArrayList<>();
        cartList.addAll(mustOrderDishs);
        for (GetShopDishResponse.TwoShopDish twoShopDish : cartList) {
            HashMap<String, Integer> mapFeed = null;//加料
            if (twoShopDish.getFeedList().size() > 0) {
                mapFeed = new HashMap<>();
                for (DishTasteBean tasteBean : twoShopDish.getFeedList()) {
                    mapFeed.put(tasteBean.getDishTasteID(), tasteBean.getValue() * twoShopDish.getCartNum());
                }
            }
            List<Integer> comboList = null;//套餐
            if (twoShopDish.getComboList() != null) {
                comboList = new ArrayList<>();
                for (DishSetDetail setDetail : twoShopDish.getComboList()) {
                    comboList.add(setDetail.getDishSetDetailID());
                }
            }
            String boxFeeStr = "";
            if (twoShopDish != null && twoShopDish.getBoxFee() != null) {
                boxFeeStr = MathUtil.saveTwoDigit2(Double.parseDouble(twoShopDish.getBoxFee()));
            }
            detailParams.add(new OrderParam.OrderDetailParam(Integer.valueOf(twoShopDish.getDishID()),
                    Integer.valueOf(twoShopDish.getDishTypeID()), boxFeeStr,
                    MathUtil.saveTwoDigit2(twoShopDish.getPrice()),
                    MathUtil.saveTwoDigit2(twoShopDish.getPrice() * twoShopDish.getCartNum()),
                    twoShopDish.getIsMustOrder(),
                    twoShopDish.getDishUnitID(), twoShopDish.getDishTasteID(), mapFeed,
                    twoShopDish.getCartNum(), null, twoShopDish.getDishName(),
                    comboList == null ? null :
                            JSON.toJSONString(comboList).replace("[", "")
                                    .replace("]", "")));

        }

        double amount = 0;
        for (int i = 0; i < cartList.size(); i++) {
            int cartNum = cartList.get(i).getCartNum();
            double price = cartList.get(i).getPrice();
            amount += cartNum * price;
        }
        OrderParam param = new OrderParam(Integer.valueOf(mShopId), tableId,
                dinnerPeople, cartList.size(), 4,
                MathUtil.saveTwoDigit2(amount), MathUtil.saveTwoDigit2(amount),
                etRemark.getText().toString(), tableFee, detailParams);
        // return JSON.toJSONString(param);
        return param;
    }

    @Override
    public void postOrderSuccess(PostOrderResponse postOrderResponse) {
        orderId = postOrderResponse.getData();
        RxBusUtil.getDefault().post(new RxEvent(CommonConstant.OpertionType.POSTORDER_SUCCESS,
                CommonConstant.OpertionType.POSTORDER_SUCCESS));
        DTLog.showMessageShort(this, postOrderResponse.getMessage());
        resetDataSet();
        if (isAccount) {
            goToAccountActivity();
            return;
        }
        finish();
        //overridePendingTransition(R.anim.activity_open, R.anim.activity_close);
    }

    @Override
    public void isNeedTableFeeSuccess(IsNeedTableFeeResponse isNeedTableFeeResponse) {
        tableFee = String.valueOf(isNeedTableFeeResponse.getData().getTableFee());
    }

    private void goToAccountActivity() {
        Intent intent = new Intent(this, AccountActivity.class);
        intent.putExtra(CommonConstant.Args.ORDER_ID, orderId);
        intent.putExtra(CommonConstant.Args.DINNER_NUM, dinnerPeople + "");
        // intent.putExtra(CommonConstant.Args.MUST_DISHS,JSON.toJSONString(mustOrderDishs));
        startActivity(intent);
        finish();
    }
}
